package cn.kgc.vue.shiro;

import cn.hutool.json.JSONUtil;
import cn.kgc.vue.commons.Const;
import cn.kgc.vue.commons.ResponseResult;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 课工场
 * @date 2024/7/3
 * @description  自定义校验token的过滤器
 */
public class WebTokenFilter extends BasicHttpAuthenticationFilter {


    //  请求是否被允许    boolean   true  放行   false  拦截
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {


        PrintWriter writer = null;
        try {
            executeLogin(request,response);
            return  true;
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=utf-8");
                writer = response.getWriter();
                ResponseResult responseResult = ResponseResult.error().code(Const.UN_AUTH).message("token异常，请重新登录");
                String jsonStr = JSONUtil.toJsonStr(responseResult);
                writer.write(jsonStr);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            return  false;
        }finally {
            if (writer!=null){
                writer.close();
            }
        }
    }


    // 执行登录方法
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {


        // 获取请求头中的token
        HttpServletRequest httpServletRequest  = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("authorization");
        if (StringUtils.isBlank(token)){
            throw  new RuntimeException("请求的是受限资源,请认证后访问");
        }
        // 获取认证主体
        Subject subject = getSubject(request, response);
        // 登录方法  username password      token  String
        JWTToken jwtToken = new JWTToken(token,request);
        subject.login(jwtToken);

        return true;
    }


    //  在执行isAccessAllowed之前先执行该方法    可以在该方法中设置跨域问题
    //  用户在发起请求时 如果请求跨域 会先发送一个options请求来判定该接口是否允许跨域    状态码未200 则说明允许跨域
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {


        HttpServletRequest  httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        // 设置响应头  允许跨域
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));

        // 判定是不是option请求  预检请求
        // 跨域时会首先发送一个options请求，options请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }



}
